package com.example.test1.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * JWT令牌生成
 */

@Component
public class JwtUtils {
    private String SECRET = "pptshuaishuai"; //密钥

    private final static int access_token_expiration = 7200;//7200秒

    public String generateJwtToken(String openId, String session_key) {
        // JWT头部分信息【Header】
        Map<String, Object> header = new HashMap<>();
        header.put("alg", "HS256"); //algorithm
        header.put("typ", "JWT");   //type

        // 载核【Payload】
        Map<String, Object> payload = new HashMap<>();
        payload.put("openid", openId);
        payload.put("session_key", session_key);

        // 声明Token失效时间
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND,access_token_expiration);

        return Jwts.builder()
                .setHeader(header)
                .setClaims(payload)
                .setId(UUID.randomUUID().toString())
                .setIssuedAt(new Date())
                .setExpiration(instance.getTime()) //过期时间
                .setSubject("user")
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();

    }

    /**
     * 检查JWT令牌是否有效
     * @param token
     * @return
     */

    public boolean checkToken(String token) {

        if (StringUtils.isEmpty(token)) return false;
        try {
            Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    /**
     * 从令牌中获取用户编号OpenId
     * @param token
     * @return
     */

    public int getOpenIdFromToken(String token) {
        if (!checkToken(token)) {
            return -1;
        }

        //解析JWT令牌的代码片段
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (int) claims.get("openid");
    }

    /**
     * 检查HTTP中的JWT令牌是否有效
     * @param request
     * @return
     */

    public boolean checkToken(HttpServletRequest request) {
        try {
            //获取JWT令牌字符串
            String token = request.getHeader("Authorization");
            return checkToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    /**
     * 从HTTP中获取用户编号OpenId
     * @param request
     * @return
     */

    public int getOpenIdFromToken(HttpServletRequest request) {
        //获取JWT令牌字符串
        String token = request.getHeader("Authorization");
        return getOpenIdFromToken(token);

    }

}
